package com.tping.leetcode;

import java.util.HashMap;

/**
 * 两数之和
 *
 * @author xiai
 * @Date 2022/12/19 21:29
 * @Version 1.0
 */
public class Solution_0001 {

    /**
     * 暴力求解
     *
     * @param nums
     * @param target
     * @return
     */
    public int[] twoSum1(int[] nums, int target) {
        int[] idx = new int[2];
        for(int i = 0; i < nums.length - 1; i++){
            for(int j = i + 1; j < nums.length; j++){
                if( nums[i] + nums[j] == target ){
                    idx[0] = i;
                    idx[1] = j;
                    return idx;
                }
            }
        }
        return idx;
    }

    /**
     * Hash表
     *
     * @param nums
     * @param target
     * @return
     */
    public int[] twoSum(int[] nums, int target){
        int len = nums.length;
        HashMap<Integer, Integer> hashMap = new HashMap<>(len -1);
        hashMap.put(nums[0], 0);
        for (int i = 1; i <= nums.length - 1; i++) {
            if( hashMap.containsKey(target - nums[i]) ){
                return new int[]{i, hashMap.get(target - nums[i])};
            }
            hashMap.put(nums[i], i);
        }
        return null;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{3, 2, 4};
        int[] twoSum = new Solution_0001().twoSum(nums, 6);
        System.out.println(twoSum[0]);
        System.out.println(twoSum[1]);
    }
}
